#include "httpclient.h"
#include <QTextCodec>
#include <QTextDecoder>
#include <QTime>

HttpClient::HttpClient(QString host, QObject* parent)
        : QObject(parent)
{
    qHost = host;
    mHttp = new QHttp(host.toAscii().data());
    finished = false;
    qCookies = "";
    qLocation = "";
    connect(mHttp, SIGNAL(responseHeaderReceived(const QHttpResponseHeader&)),
        SLOT(responseHeaderReceived(const QHttpResponseHeader&)));
    connect(mHttp, SIGNAL(readyRead(const QHttpResponseHeader&)),
        SLOT(readyRead(const QHttpResponseHeader&)));
    connect(mHttp, SIGNAL(done(bool)), SLOT(done(bool)));
};

HttpClient::~HttpClient()
{
    mHttp->close();
    mHttp->closeConnection();
    delete mHttp;
}

void HttpClient::setProxyInfo(bool useProxy, QString proxyHost, int proxyPort, bool useAuthorization, QString proxyUserName, QString proxyPassword)
{
    if (useProxy)
    {
        if (useAuthorization)
        {
            qDebug(" * Using proxy with auth (login: %s, password: %s)", proxyUserName.toAscii().data(), "*****");
            mHttp->setProxy(proxyHost, proxyPort, proxyUserName, proxyPassword);
        }
        else
        {
            qDebug(" * Using proxy without auth");
            mHttp->setProxy(proxyHost, proxyPort, "", "");
        }
    }

}

void HttpClient::addCookies(QString cookies)
{
    qCookies.append(cookies);
}

void HttpClient::setTimeout(int timeout)
{
    waitTimeout = timeout;
}

void HttpClient::doRequest(QString qHost, QString url, QByteArray content)
{
    finished = false;
    QHttpRequestHeader req("POST", url);
    req.addValue("Host", qHost);
    req.addValue("Cookie", qCookies);
    req.addValue("Cookie2", "$Version=1");
    req.addValue("Referer", "http://"+qHost+"/");
    req.setContentType("application/x-www-form-urlencoded");
    req.setContentLength(content.length());

    qDebug(" * POST '%s'", url.toAscii().data());
    data = "";
    response = 0;
    mHttp->request(req, content);
}

void HttpClient::doRequest(QString qHost, QString url)
{
    finished = false;
    QHttpRequestHeader req("GET", url);
    req.addValue("Host", qHost);
    req.addValue("Cookie", qCookies);
    req.addValue("Cookie2", "$Version=1");
    req.addValue("Referer", "http://"+qHost+"/");

    qDebug(" * GET '%s'", url.toAscii().data());
    data = "";
    response = 0;
    mHttp->request(req);
}

void HttpClient::wait()
{
//    QTime dieTime = QTime::currentTime().addMSecs(waitTimeout);
    while((!finished)/* && (QTime::currentTime() < dieTime)*/)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 10);
}

void HttpClient::done(bool error)
{
	QTextCodec* codec = QTextCodec::codecForHtml(data);
	QTextDecoder* deco = codec->makeDecoder();
//        qDebug(" * Done. %d bytes in, decoding as %s.", data.length(), codec->name().data());
	QString s = deco->toUnicode(data);
        qData = s;
        finished = true;
};

void HttpClient::responseHeaderReceived(const QHttpResponseHeader& resp)
{
        qDebug(" * Response %d: %s.", resp.statusCode(), resp.reasonPhrase().toAscii().data());
        response = resp.statusCode();
        for (int i = 0; i < resp.values().count(); ++i)
        {
            if (resp.values().at(i).first.toAscii() == "Set-Cookie")
            {
                QString cur = resp.values().at(i).second.toAscii();
                int pos = resp.values().at(i).second.toAscii().indexOf(';');
                cur.truncate(pos);
                qDebug(" * Received new cookie: %s", cur.toAscii().data());
                qCookies.append(cur+"; ");
            }
            if (resp.values().at(i).first.toAscii() == "Location")
                qLocation = resp.values().at(i).second.toAscii();
        }
}

void HttpClient::readyRead(const QHttpResponseHeader &resp)
{
	outData(mHttp->readAll());
}

void HttpClient::outData(QByteArray data)
{
	this->data += data;
};

#include "moc_httpclient.cpp"
